package com.csw.flink.core

import java.time.Duration
import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer


/**
  * 基于事件时间的滑动窗口的触发条件：
  * 1、水位线(Watermark)大于等于窗口的结束时间
  * 2、窗口内有数据
  * 水位线 默认等于最新的一条数据的时间戳
  */
object Demo05EventTime {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
      * 修改时间模式为事件时间
      */
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)


    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    properties.setProperty("group.id", "csw")
    //    properties.setProperty("auto.offset.reset", "earliest") //earliest：读取所有数据 latest：读取最新数据


    /*
    数据时间
    1,1622459464000
    1,1622459465000
    1,1622459466000
    1,1622459466000
    1,1622459466000
    1,1622459467000
    1,1622459468000
    1,1622459469000
    1,1622459470000
    1,1622459471000
    1,1622459472000
    1,1622459476000
     */


    val consumer: FlinkKafkaConsumer[String] = new FlinkKafkaConsumer[String](
      "event_time", new SimpleStringSchema(), properties)

    //读取最新数据
//    consumer.setStartFromLatest()

    val kafkaDS: DataStream[String] = env.addSource(consumer)

    val kvDS: DataStream[Event] = kafkaDS.map(line => {
      val split: Array[String] = line.split(",")

      Event(split(0), split(1).toLong, 1)
    })


    //默认水位线等于最新一条数据的时间戳
    //val eventDS: DataStream[Event] = kvDS.assignAscendingTimestamps(event => event.ts)

    //指定哪一个字段为事件时间字段
    //指定事件最大延迟时间和时间字段
    //相当于把水位线前移
    val eventDS: DataStream[Event] = kvDS.assignTimestampsAndWatermarks(
      new BoundedOutOfOrdernessTimestampExtractor[Event](Time.seconds(5)) {
        //返回事件时间的字段
        override def extractTimestamp(element: Event): Long = {

          element.ts
        }
      })
    /**
      * 统计最近5秒每个id的数量
      * keyby之后才可以使用窗口函数
      */

    val countDS: DataStream[Event] = eventDS.keyBy(_.id).timeWindow(Time.seconds(5)).sum("count")


    countDS.print()

    env.execute()
  }

  case class Event(id: String, ts: Long, count: Long)

}
